package edu.pku.sei.transformation.editor.actions;


import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.transformation.codegen.CodegenAdapter;
import edu.pku.sei.transformation.editor.model.implement.ICodegenElement;
import edu.pku.sei.transformation.editor.model.implement.TransformationCode;
import edu.pku.sei.transformation.editor.views.dialogs.ComfirmDialog;
import edu.pku.sei.transformation.editor.views.editor.TextEditor;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;

public class CodegenAction extends Action {
	private ICodegenElement transformation = null;
	private CodegenAdapter adapter = null;
	
	public CodegenAction(Object selectElement, CodegenAdapter adapter) {
		setText("generate "+adapter.getLanguage());
		setImageDescriptor(IconsProvider
				.getImageDescriptor(IconsProvider.FILE_EXPORT_ICO));
		if (selectElement instanceof ICodegenElement)
			this.transformation = (ICodegenElement) selectElement;
		this.adapter = adapter;
	}
	
	@Override
	public boolean isEnabled() {
		if (adapter == null)
			return false;
		else
			return adapter.canGenerate(transformation);
		
	}

	@Override
	public void run() {
		if (transformation.getCode(adapter.getLanguage()) != null) {
			Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
			.getShell();
			ComfirmDialog dialog = new ComfirmDialog(shell, "code exist, do you want to override it?");
			int result = dialog.open();
			if (result == SWT.OK) {
				System.out.println("ok");
				if (adapter.generateCode(transformation)) {
					TransformationCode code = transformation.getCode(adapter.getLanguage());
					try {
						code.getFile().refreshLocal(1, null);
						TextEditor.openInEditor(code.getFile());
					} catch (CoreException e) {
						e.printStackTrace();
					}
				}	
			} else {
				System.out.println("cancel");
				FileDialog file = new FileDialog(shell, SWT.SAVE);
				String s = file.open();
				if (s!=null){
					adapter.generateCodeToFile(transformation, s);
					try {
						TextEditor.openInDefaultTextEditor(s);
					} catch (PartInitException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			if (adapter.generateCode(transformation)) {
				TransformationCode code = transformation.getCode(adapter.getLanguage());
				try {
					code.getFile().refreshLocal(1, null);
					TextEditor.openInEditor(code.getFile());
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}			
		}
		
	}
}
